#用户注册时调用初始化积分
from coreServices.models import PointsRecord
from userServer.models import UserInfo
from django.core.exceptions import ObjectDoesNotExist

# \userServer\dao\PointsRecordDao.py
def initPoints(userId):
    userInfo = UserInfo.objects.get(id=userId)
    PointsRecord.objects.create(userId=userInfo, points_balance=1000, points_type='注册积分')
    return True
#消耗积分积
def consumePoints(user_id,points):
    try:
        # 获取 UserInfo 实例
        user_info = UserInfo.objects.get(id=user_id)
        print(f"User Info retrieved: {user_info}")

        try:
            # 尝试获取用户的积分记录
            pointsRecord = PointsRecord.objects.get(userId=user_info)
            print(f"Points Record retrieved: {pointsRecord}")

            # 消耗积分
            if pointsRecord.points_balance >= points:
                pointsRecord.points_balance -= points
                pointsRecord.points_consume += points
                pointsRecord.save()
                print(f"Points consumed: {points}, New balance: {pointsRecord.points_balance}")
            else:
                print(f"User {user_id} does not have enough points to consume.")
                # 或者记录日志，抛出自定义异常等
        except ObjectDoesNotExist:
            # 如果积分记录不存在，则创建一个新的积分记录
            pointsRecord = PointsRecord(userId=user_info, points_balance=1000 - points, points_consume=points,
                                        points_type='consumption')
            pointsRecord.save()
            print(f"New Points Record created: {pointsRecord}")
    except ObjectDoesNotExist:
        print(f"UserInfo with id {user_id} does not exist.")
        # 或者记录日志，抛出自定义异常等